<template>
  <div class="permissions-container">
    <div class="header">
      <h2>权限管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增权限
      </el-button>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input v-model="searchForm.code" placeholder="请输入权限编码" clearable />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="searchForm.type" placeholder="请选择权限类型" clearable>
            <el-option label="菜单" value="menu" />
            <el-option label="操作" value="action" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.isActive" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="tableData"
      v-loading="loading"
      stripe
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="权限名称" width="200" />
      <el-table-column prop="code" label="权限编码" width="200" />
      <el-table-column prop="type" label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="row.type === 'menu' ? 'primary' : 'success'">
            {{ row.type === 'menu' ? '菜单' : '操作' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="resource" label="资源" />
      <el-table-column prop="action" label="动作" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="isActive" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
            v-if="row.type === 'menu'"
            type="success"
            size="small"
            @click="handleAddChild(row)"
          >
            添加子权限
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 权限表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="menu">菜单</el-radio>
            <el-radio label="action">操作</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="parentPermission" label="父权限">
          <el-input :value="parentPermission.name" disabled />
        </el-form-item>
        <el-form-item label="资源" prop="resource">
          <el-input v-model="form.resource" placeholder="请输入资源标识" />
        </el-form-item>
        <el-form-item label="动作" prop="action">
          <el-input v-model="form.action" placeholder="请输入动作标识" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-radio-group v-model="form.isActive">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { Permission } from '@/types/auth'

/**
 * 搜索表单数据
 */
const searchForm = reactive({
  name: '',
  code: '',
  type: '',
  isActive: undefined as boolean | undefined
})

/**
 * 表格数据
 */
const tableData = ref<Permission[]>([])
const loading = ref(false)

/**
 * 分页数据
 */
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

/**
 * 对话框相关
 */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitting = ref(false)
const parentPermission = ref<Permission | null>(null)

/**
 * 表单数据
 */
const form = reactive({
  id: null as number | null,
  name: '',
  code: '',
  type: 'menu' as 'menu' | 'action',
  resource: '',
  action: '',
  description: '',
  isActive: true,
  parentId: null as number | null
})

/**
 * 表单验证规则
 */
const rules = {
  name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入权限编码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择权限类型', trigger: 'change' }],
  resource: [{ required: true, message: '请输入资源标识', trigger: 'blur' }],
  action: [{ required: true, message: '请输入动作标识', trigger: 'blur' }],
  isActive: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

/**
 * 表单引用
 */
const formRef = ref<FormInstance>()

/**
 * 格式化日期
 */
const formatDate = (date: string) => {
  return new Date(date).toLocaleString()
}

/**
 * 获取权限列表
 */
const fetchPermissions = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取权限列表
    // const response = await request.get('/api/permissions', {
    //   params: {
    //     page: pagination.page,
    //     size: pagination.size,
    //     ...searchForm
    //   }
    // })
    // tableData.value = response.data.data
    // pagination.total = response.data.total
    
    // 模拟数据
    tableData.value = [
      {
        id: 1,
        name: '用户管理',
        code: 'user',
        type: 'menu',
        resource: 'user',
        action: '*',
        description: '用户管理模块',
        isActive: true,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: '2024-01-01T00:00:00Z',
        children: [
          {
            id: 11,
            name: '查看用户',
            code: 'user:view',
            type: 'action',
            resource: 'user',
            action: 'view',
            description: '查看用户列表',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          },
          {
            id: 12,
            name: '创建用户',
            code: 'user:create',
            type: 'action',
            resource: 'user',
            action: 'create',
            description: '创建新用户',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          }
        ]
      },
      {
        id: 2,
        name: '角色管理',
        code: 'role',
        type: 'menu',
        resource: 'role',
        action: '*',
        description: '角色管理模块',
        isActive: true,
        createdAt: '2024-01-01T00:00:00Z',
        updatedAt: '2024-01-01T00:00:00Z',
        children: [
          {
            id: 21,
            name: '查看角色',
            code: 'role:view',
            type: 'action',
            resource: 'role',
            action: 'view',
            description: '查看角色列表',
            isActive: true,
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z'
          }
        ]
      }
    ]
    pagination.total = 2
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.page = 1
  fetchPermissions()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    type: '',
    isActive: undefined
  })
  pagination.page = 1
  fetchPermissions()
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchPermissions()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchPermissions()
}

/**
 * 新增权限
 */
const handleAdd = () => {
  dialogTitle.value = '新增权限'
  parentPermission.value = null
  Object.assign(form, {
    id: null,
    name: '',
    code: '',
    type: 'menu',
    resource: '',
    action: '',
    description: '',
    isActive: true,
    parentId: null
  })
  dialogVisible.value = true
}

/**
 * 添加子权限
 */
const handleAddChild = (parent: Permission) => {
  dialogTitle.value = '新增子权限'
  parentPermission.value = parent
  Object.assign(form, {
    id: null,
    name: '',
    code: '',
    type: 'action',
    resource: parent.resource,
    action: '',
    description: '',
    isActive: true,
    parentId: parent.id
  })
  dialogVisible.value = true
}

/**
 * 编辑权限
 */
const handleEdit = (row: Permission) => {
  dialogTitle.value = '编辑权限'
  parentPermission.value = null
  Object.assign(form, {
    id: row.id,
    name: row.name,
    code: row.code,
    type: row.type,
    resource: row.resource,
    action: row.action,
    description: row.description || '',
    isActive: row.isActive,
    parentId: null
  })
  dialogVisible.value = true
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // TODO: 调用API保存权限
    // if (form.id) {
    //   await request.put(`/api/permissions/${form.id}`, form)
    //   ElMessage.success('更新权限成功')
    // } else {
    //   await request.post('/api/permissions', form)
    //   ElMessage.success('创建权限成功')
    // }
    
    ElMessage.success(form.id ? '更新权限成功' : '创建权限成功')
    dialogVisible.value = false
    fetchPermissions()
  } catch (error) {
    ElMessage.error('保存权限失败')
  } finally {
    submitting.value = false
  }
}

/**
 * 删除权限
 */
const handleDelete = async (_row: Permission) => {
  try {
    await ElMessageBox.confirm('确定要删除该权限吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // TODO: 调用API删除权限
    // await request.delete(`/api/permissions/${row.id}`)
    
    ElMessage.success('删除权限成功')
    fetchPermissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除权限失败')
    }
  }
}

onMounted(() => {
  fetchPermissions()
})
</script>

<style scoped>
.permissions-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  margin: 0;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>